package com.imooc.mmall.service.impl;

import com.imooc.common.ServerResponse;
import com.imooc.mmall.dao.UserMapper;
import com.imooc.mmall.exception.UserException;
import com.imooc.mmall.pojo.User;
import com.imooc.mmall.service.IUserService;
import com.imooc.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.sql.Timestamp;
import java.util.Date;


/**
 * Created by geely
 */
@Service("iUserService")
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public int getUserCount() {
        return userMapper.getUserCount();
    }

    @Override
    public User selectByPrimaryKey(Integer id) {
        return userMapper.selectByPrimaryKey(id);
    }


    @Override
    public ServerResponse<User> login(String username, String password) {
        int resultCount = userMapper.checkUsername(username);
        if(resultCount == 0 ){
            return ServerResponse.createByErrorMessage("用户名不存在");
        }

        String md5Password = MD5Util.MD5EncodeUtf8(password);
        User user  = userMapper.selectLogin(username,md5Password);
        if(user == null){
            throw new UserException("用户名或者密码不正确！");
//            return ServerResponse.createByErrorMessage("密码错误");
        }

        user.setPassword(org.apache.commons.lang3.StringUtils.EMPTY);
        return ServerResponse.createBySuccess("登录成功",user);
    }

    @Override
    public ServerResponse<User> saveUser(User user) {
//        User a = new User();
//        a.setPassword("111");
//        a.setUsername("tom");
//        a.setRole(0);
            user.setCreateTime(new Date());
            user.setUpdateTime(new Timestamp(System.currentTimeMillis()));
//        System.out.println("受影响行数："+userMapper.insert(a));
//        System.out.println("aaaaaaaaaaaaaa");
        userMapper.insert(user);
        return ServerResponse.createBySuccess("保存成功",user);
    }

}
